<template>
  <div class="portal-ui">
    <el-container class="portal-ui">
      <el-header class="portal-ui-header"><span class="title">微应用管理系统</span></el-header>
      <el-container class="portal-ui-main">
        <el-aside width="200px">
          <!--      <el-menu @select="changeMenu" router>-->
          <!--        <el-menu-item v-for="item in userMenus[0].children" :index="item.value"  :key="item.value">-->
          <!--          <template #title>{{ item.name }}</template>-->
          <!--        </el-menu-item>-->
          <!--      </el-menu>-->
          <el-menu
              @select="changeMenu"
              :default-active="activeIndex"
              router>
            <template v-for="menuItem in userMenus">
              <el-submenu v-if="menuItem.children" :index="menuItem.value" :key="menuItem.value">
                <template slot="title">{{menuItem.name}}</template>
                <template v-slot="title">
                  <!--              <i :class="menuItem.icon"></i>-->
                  {{ menuItem.name }}
                </template>
                <el-menu-item v-for="child in menuItem.children" :index="child.value" :key="child.value">
                  <!--              <i :class="child.icon"></i>-->
                  {{ child.name }}
                </el-menu-item>
              </el-submenu>
              <el-menu-item v-else :index="menuItem.value" :key="menuItem.value + '1'">
                <!--            <i :class="menuItem.icon"></i>-->
                {{ menuItem.name }}
              </el-menu-item>
            </template>
          </el-menu>
        </el-aside>
        <el-main style="margin-left: 8px">
          <!-- 循环生成容器，每一个微应用使用独立的容器，自己控制微应用的显隐 -->
          <div
              v-for="item in microApps"
              :key="item.name"
              :id="item.container.slice(1)"
              v-show="$route.path.startsWith(item.prefixPath)"
          ></div>
          <!-- 缓存主应用的路由 -->
          <keep-alive>
            <router-view></router-view>
          </keep-alive>
        </el-main>
      </el-container>
      <el-footer class="portal-ui-footer">
        <el-tabs v-model="currentTab" @tab-remove="removeTab" @tab-click="changeTab"
                 tab-position="bottom"
                 :closable="false">
          <el-tab-pane
              v-for="item in allTabs"
              :key="item.value"
              :label="item.name"
              :name="item.value "
              :closable="item.affix"
          >
          </el-tab-pane>
        </el-tabs>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { loadMicroApp, initGlobalState } from 'qiankun';
import {getRouters} from "@/api/system/rule";
// 初始化 state
const actions = initGlobalState({});
export default {
  data() {
    return {
      activeIndex:'',
      userMenus:[],
      menuData: [
        // { name: '子应用1的home', value: '/app-vue-hash/#/layout1/home' },
        // { name: '子应用1的about', value: '/app-vue-hash/#/layout2/about' },
        // { name: '子应用2的home', value: '/app-vue-history/' },
        // { name: '子应用2的about', value: '/app-vue-history/about' },
        // { name: '主应用的about', value: '/about' },
      ],
      allTabs: [{ name: '我的工作台', value: '/dashboard' , affix: false}],
      currentTab: '/dashboard',
      loadedApp: {}, // 已加载的微应用
      microApps: [
        // {
        //   name: 'app-vue-hash',
        //   entry: 'http://localhost:1111',
        //   container: '#app-vue-hash',
        //   prefixPath: '/app-vue-hash',
        // },
        // {
        //   name: 'app-vue-history',
        //   entry: 'http://localhost:2222',
        //   container: '#app-vue-history',
        //   prefixPath: '/app-vue-history',
        // }
      ], // 微应用的数据
    }
  },
  created() {
    getRouters().then((res)=>{
      this.userMenus = res.data.userMenus
      res.data.microApp.map(p=>{
        this.microApps.push({name:p.appName,entry:p.appEntry,container:'#'+p.appName,prefixPath:'/'+p.appName})
      })
      console.log(this.userMenus)
    })
  },
  mounted() {
    this.$router.push('/dashboard');
  },
  methods: {
    changeMenu (indexPath) {
      if (this.currentTab === indexPath) return;
      const existTab = this.allTabs.find(item => item.value === indexPath);
      if (existTab) {
        this.currentTab = existTab.value;
      } else {
        // 先判断是子应用还是主应用，再判断子应用是否已加载
        const microApp = this.microApps.find(item => indexPath.includes(item.prefixPath));
        if (microApp) {
          const childRoutePath = indexPath.replace(microApp.prefixPath,'');
          if (!this.loadedApp[microApp.name]) {
            const app = loadMicroApp(microApp); // 多了个参数 prefixPath，但是可以忽略
            this.loadedApp[microApp.name] = {
              app,
              childRoute: [],
            };
          }
          // 如果子应用已加载，将子应用的路由纪录到数组中，并通知子应用增加 keep-alive 的 include
          this.loadedApp[microApp.name].childRoute.push(childRoutePath);
          actions.setGlobalState(this.loadedApp);
        }
        let resultMenu = null
        function getTreeItem (data, indexPath) {
          data.map(item => {
            if (item.value === indexPath) {
              resultMenu =  item;	// 结果赋值
            } else {
              if (item.children) {
                getTreeItem(item.children, indexPath);
              }
            }
          });
        }
        getTreeItem(this.userMenus,indexPath)
        // 添加 tab 纪录
        // const selectMenu = this.userMenus.find(item => item.value === indexPath);
        this.allTabs.push(resultMenu);
        this.activeIndex = resultMenu.value
        this.currentTab = indexPath;
      }
    },
    removeTab (tab) {
      if (tab==='/dashboard'){
        return
      }
      // 先判断是子应用还是主应用
      const microApp = this.microApps.find(item => tab.includes(item.prefixPath));
      if (microApp) {
        // 移除子应用已缓存的应用
        const childRoutePath = tab.replace(microApp.prefixPath,'');
        const childRouteIndex = this.loadedApp[microApp.name].childRoute.indexOf(childRoutePath);
        this.loadedApp[microApp.name].childRoute.splice(childRouteIndex, 1);
        actions.setGlobalState(this.loadedApp);
        // 再当前微应用的页面是否已全部关闭
        if (this.loadedApp[microApp.name].childRoute.length === 0) {
          this.loadedApp[microApp.name].app.unmount();
          this.loadedApp[microApp.name] = null;
        }
      }
      const deleteTab = this.allTabs.findIndex(item => item.value === tab);
      this.allTabs.splice(deleteTab, 1);
      const oneTab = this.allTabs[this.allTabs.length-1].value
      this.currentTab = oneTab
      this.$router.push(oneTab)
      this.activeIndex = oneTab

    },
    changeTab (tab) {
      if(tab.name === this.$route.path) return;
      this.$router.push(tab.name);
    }
  },
}
</script>

<style scoped>

.el-menu{
  height: 100%;
}

.el-main {
  background: #ffffff;
}

body > .el-container {
  //margin-bottom: 40px;
  //height: 100%;
}

el-footer{
  height: 40px;
  background: rgb(255,255,255);
}
.el-header{
  //line-height: 60px;
  //height: auto;
}
.portal-ui{
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: #e5e5e5;
}
.portal-ui-header{
  background: rgb(255,255,255);
  line-height: 60px;
  .title{
    font-size: 30px;
  }
}
.portal-ui-main{
  padding: 12px 12px 12px 0;
  overflow: hidden;
}
.portal-ui-footer{
  background: rgb(255,255,255);
}
</style>
